package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: 李旭
 * @Time: 11:11
 * @Description:
 */
@Service
public class TestServiceImpl implements TestService {

    private final Lock lock = new ReentrantLock();
    @Autowired
    private RedisTemplate redisTemplate;

    //分布式锁
    @Override
    public void lock() {//不见不散
        //分布式锁   Redis中存在了Lock 表示已经上锁  不存在表示未上锁  setnx
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "1213");
        if(lock){
            //lock : true 表示  未上锁
            Integer num = (Integer) redisTemplate.opsForValue().get("num");
            num++;
            redisTemplate.opsForValue().set("num",num);
            //删除Lock 表示解锁
            redisTemplate.delete("lock");
        }else{
            //lock : false 表示 已经上锁了
            //TimeUnit.SECONDS.sleep(2);
            lock();
        }
    }


    //本地锁代码测试
/*    @Override
    public void lock() {
        lock.lock();
        try {
            Integer num = (Integer) redisTemplate.opsForValue().get("num");
            num++;
            redisTemplate.opsForValue().set("num",num);
        } finally {
            lock.unlock();
        }
    }*/
}
